import signal
import sys

import pytest

import ray
from ray._common.test_utils import wait_for_condition

import psutil


def get_pid(name):
    pids = psutil.process_iter()
    for pid in pids:
        if name in pid.name():
            return pid.pid
    return -1


@pytest.mark.skipif(sys.platform == "win32", reason="Not support on Windows.")
def test_kill_raylet_signal_log(ray_start_regular):
    session_dir = ray._private.worker._global_node.get_session_dir_path()
    raylet_out_path = "{}/logs/raylet.err".format(session_dir)
    pid = get_pid("raylet")
    assert pid > 0
    p = psutil.Process(pid)
    p.send_signal(signal.SIGABRT)
    p.wait(timeout=15)

    def check_for_sigabrt_in_log():
        with open(raylet_out_path) as f:
            s = f.read()
            return "SIGABRT" in s

    wait_for_condition(check_for_sigabrt_in_log)


if __name__ == "__main__":
    sys.exit(pytest.main(["-sv", __file__]))
